go to previous page   go to home page   go to next page

Answer:

Here is one correct answer:

  public static void main ( String[] args )
  {
    Goods   toy ;
    Taxable tax = new Toy ( "Building Blocks", 1.49, 6 );

    toy = (Toy)tax;
    toy.display();
    System.out.println( "Tax: "+ ((Taxable)toy).calculateTax() );
  }

Yet More Practice

The first type cast in the answer must cast tax to a type Goods (or an ancestor). The second must cast toy to Taxable or to a class that implements Taxable.

When you think about such problems, remember that at compile time objects do not exist. The compiler knows what methods are available with a reference variable based only on the type of the variable.

For example, in the above, only the calculateTax() method would be available with tax. At run time the object tax points to has more methods avaialble. To say this in the code, use a type cast.

Here is another possible answer:

  public static void main ( String[] args )
  {
    Goods   toy ;
    Taxable tax = new Toy ( "Building Blocks", 1.49, 6 );

    toy = (Goods)tax;
    toy.display();
    System.out.println( "Tax: "+ ((Toy)toy).calculateTax() );
  }

QUESTION 23:

Is this answer correct?